package obsolete;

import java.util.Timer;
import java.util.TimerTask;

import org.NooLab.utilities.logging.PrintLog;

import org.NooLab.glue.MessageBoard;
import org.NooLab.glue.components.SenderWrap;




public class OpeningHandshake {

	int shakingPort ;
	String participantsRole ; 
	long transactionID;
	MessageBoard messageBoard;
	boolean processCompleted=false;
	
	PrintLog out = new PrintLog(2,true);
	
	public OpeningHandshake( MessageBoard messageboard, int port, String clientrole, long transactionid ){
		
		messageBoard = messageboard;
		
		shakingPort = port;
		participantsRole = clientrole ; 
		transactionID = transactionid ;
		
	}
	
	
	public boolean checkAvailability(){
		boolean rB=false, timedOut;
		String xmloutmsg="" ;
		int z;
		CSender cSender ;
		
		// create a very short connection test xml
		xmloutmsg = "" ;
		
		
		cSender = new CSender(xmloutmsg);
		

				out.print(4, "...waiting for confirmation of interaction...");
		
		int limit = 80; // 80 = max 8 seconds, (if debug -> ">1000")
		z = 1;
		timedOut = false;
		// "processCompleted" is set in update() => handlingRegistrationReply()
		while ((processCompleted == false) && (timedOut == false)) {
			
			
			z++ ;
		}

		
		return rB;
	}
	
	
	

	class CSender implements Runnable{
		String xml;
		boolean timedOut;
		Thread regsendingThrd;
		int timeOut = 1200 ; 
		boolean enforcedStop=false;
		
		public CSender(String xml) {
			this.xml = xml;

			regsendingThrd = new Thread(this,"CSender");
			regsendingThrd.start();
			
			new Timer(true).schedule(new TimerTask() {
			      public void run() {
			        out.print(5,"Requesting stop of thread...");
			        requestStop();
			      }
			    }, timeOut);
		}

		@SuppressWarnings("static-access")
		public void requestStop() {
			enforcedStop = true;
			try {
				Thread.currentThread().sleep(200);
			} catch (InterruptedException e) {}
			
			try {
				regsendingThrd.join();
			} catch (InterruptedException e) {}
		}
		
		
		@SuppressWarnings("static-access")
		private void regSendingHandler() {

			int z, r;

			out.print(3,"...sending request for registration to MessageBoard...");
			SenderWrap sender = new SenderWrap(messageBoard);
			
			processCompleted = false;
			z = 0;
			r = -1;
			while ((r < 0) && (z < 5) && (enforcedStop==false)) {
				r = 0;
				
				sender.sendingMessage( xml, shakingPort );
				try {
					if (r < 0) {
						Thread.currentThread().sleep(200);
					}
					;
				} catch (Exception e) {
				}
				z++;
			}
		}

		@Override
		public void run() {
			regSendingHandler();
		}
		
		
	}
	
}
